package com.brucekong.slm.controller.upload;


import com.brucekong.slm.common.Result;
import com.brucekong.slm.common.UploadUtil;
import com.brucekong.slm.model.upload.FileDomain;
import com.brucekong.slm.model.user.UserDomain;
import com.brucekong.slm.service.upload.FileService;
import com.brucekong.slm.service.user.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/upload")
@Slf4j
@Api(value = "上传模块", tags = "上传模块")
public class UploadController {
    @Autowired
    private FileService fileService;
    @Autowired
    private UserService userService;

    private Result result = new Result();

    /**
     * 单文件上传
     */
    @ResponseBody
    @PostMapping("/file")
    @SuppressWarnings("unchecked")
    @ApiOperation(value = "单文件上传", notes = "每次一个文件的上传", code = 200, produces = "application/json", responseContainer = "Map", response = Result.class)
    @ApiImplicitParam(value = "文件", name = "file", required = true, dataType = "string", paramType = "query")
    public Result upload(MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException, JSONException, ParseException {

        // 调用工具类完成上传，返回相关数据到页面
        Map<String, Object> uploadResult = UploadUtil.singleupload(file, request);
        // 组织file格式
        FileDomain fileDomain = new FileDomain();
        // 如果这里为空，直接返回保存失败
        if (uploadResult != null) {
            fileDomain.setRealName(uploadResult.get("realName").toString());
            fileDomain.setSaveName(uploadResult.get("saveName").toString());
            fileDomain.setSize(Double.parseDouble(uploadResult.get("size").toString()));
            Timestamp ts = new Timestamp(System.currentTimeMillis());
            try {
                ts = Timestamp.valueOf(uploadResult.get("time").toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            fileDomain.setTime(ts);

            // 获取所有的file，取最大的id数
            int maxId = 0;
            try {
                maxId = fileService.getMaxId();
            } catch (Exception e) {
                System.out.println("当前数据库中还没有记录");
            }
            maxId += 1;
            fileDomain.setId(maxId);

            fileDomain.setUrl(uploadResult.get("url").toString());
            fileDomain.setType(uploadResult.get("type").toString());

            HttpSession session = request.getSession();
            String userName = session.getAttribute("userName").toString();
            UserDomain userDomain = userService.getUserWithoutPasswordByUserName(userName);
            fileDomain.setUserId(userDomain.getId().toString());

            fileService.save(fileDomain);
            // 这里再去用图片id查找保存的对象，如果为空则直接返回保存失败
            FileDomain fileDomainAgain = fileService.getFileBySaveName(uploadResult.get("saveName").toString());
            // 否则保存成功，返回成功参数
            if (fileDomainAgain.getRealName().equals(uploadResult.get("realName").toString())) {
                result.setCode(0);
                result.setSuccess(true);
                result.setMsg("图片保存成功！");
                fileDomain.setUrl("我是隐藏的，通过图片的saveName获取图片吧");
                result.setData(fileDomain);
            } else {
                result.setCode(1);
                result.setSuccess(false);
                result.setMsg("图片保存失败");
                result.setData(null);
            }
        } else {
            result.setCode(1);
            result.setSuccess(false);
            result.setMsg("图片保存失败");
            result.setData(null);
        }

        return result;

    }

    /**
     * 多文件上传(layui中的多文件上传，会请求多次，分成多个单个上传，所以直接用上面的upload即可)
     */
    @ResponseBody
    @PostMapping("mutilfile")
    @SuppressWarnings("unchecked")
    @ApiOperation(value = "多文件上传", notes = "一次可以上传多个文件", code = 200, produces = "application/json", responseContainer = "Map", response = Result.class)
    @ApiImplicitParam(value = "files", name = "mutilfile", required = true, dataType = "string", paramType = "query")
    public Result uploadMutilFile(MultipartFile[] files, HttpServletRequest request) throws IllegalStateException, IOException, JSONException {
        //调用工具类完成上传，返回相关数据到页面
        List<Map<String, Object>> uploadResults = UploadUtil.mutilUpload(files, request);
        // TODO 这里拿到返回的上传信息，去数据库查询是否保存成功，然后返回result即可
        result.setCode(0);
        result.setSuccess(true);
        result.setMsg("图片保存成功");
        result.setData(uploadResults);
        return result;
    }
}
